<?php

namespace App\Admin\Extensions;

use App\Library\Util\ToolUtil;
use App\Models\ExcelRule;
use App\Models\ExcelTemplate;
use App\Models\WpsFormAnswer;
use App\Models\WpsFormList;
use Encore\Admin\Grid\Exporters\AbstractExporter;
use Illuminate\Support\Facades\Storage;
use Rap2hpoutre\FastExcel\FastExcel;
use Rap2hpoutre\FastExcel\SheetCollection;

class WpsFormExport extends AbstractExporter
{

    public function export()
    {
        $params = request()->all();
        $wpsFormId = $params['wps_form_id'];
        $wpsForm = WpsFormList::query()->where('id', $wpsFormId)->first();
        if (empty($wpsForm)) {
            echo "表单信息不存在";
            die;
        }
        $tplId = $wpsForm['excel_template_id'];
        if (empty($tplId)) {
            echo "表单未配置模版ID";
            die;
        }
        $excelTemplate = ExcelRule::query()->where('template_id', $tplId)->get();
        if ($excelTemplate->isEmpty()) {
            echo "模版未配置";
            die;
        }
        $array = [];
        $data = WpsFormAnswer::query()->where('wps_form_id', $wpsFormId)->get();
        $answers = $data->pluck('answer');
        foreach ($excelTemplate as $item) {
            $temp = [];
            $configJson = $item['config_json'] ?: [];
            if (empty($configJson)) {
                continue;
            }
            $isEmptyField = $configJson['is_empty'] ?? '';
            $singleData = array_values($configJson['single_data'] ?? []);
            $multiData = array_values($configJson['multi_data'] ?? []);
            $tag = $item['id'] . '_' . $item['title'];
            foreach ($answers as $answer) {
                $answer = array_values($answer);
                $t = [];
                if ($singleData) {
                    foreach ($singleData as $sv) {
                        $svValue = '';
                        $svColumn = $sv['value'];
                        if (!empty($svColumn)) {
                            $index = ToolUtil::getInstance()->getColumnIndex($svColumn);
                            $svValue = $answer[$index] ?? '';
                            if (is_array($svValue) && $svValue['date']) {
                                $svValue =  date('Y/m/d', strtotime($svValue['date']));

                            }
                        }
                        $t[$sv['key']] = $svValue;
                    }
                }
                $tempM = [];
                $groupList = [];
                if ($multiData) {
                    $fieldArr = [];
                    $length = count(explode(',', array_values($multiData)[0]['value']));

                    for ($i = 0; $i < $length; $i++) {
                        foreach ($multiData as $multiDatum) {
                            $mvColumn = $multiDatum['value'];
                            if (!empty($mvColumn)) {
                                $mvColumnArr = explode(',', $mvColumn);
                                $fieldArr[$i][] = $multiDatum['key'] . '_' . $mvColumnArr[$i];
                            }
                        }
                    }

                    foreach ($fieldArr as $mvColumnIndexArr) {
                        $group = [];
                        foreach ($mvColumnIndexArr as $mvColumnIndexStr) {
                            list($mvKey, $mvColumnIndex) = explode('_', $mvColumnIndexStr);
                            $mvIndex = ToolUtil::getInstance()->getColumnIndex($mvColumnIndex);
                            $mvValue = $answer[$mvIndex] ?? '';
                            if (is_array($mvValue) && $mvValue['date']) {
                                $mvValue = date('Y/m/d', strtotime($mvValue['date']));
                            }
                            if ($mvValue) {
                                $group[$mvKey] = $mvValue;
                                $tempM[$mvKey][] = $mvValue;
                            }
                        }
                        if ($group) {
                            $groupList[] = $group;
                        }
                    }

                }
//                if ($tempM) {
//                    foreach ($tempM as $mKey => $tempDatum) {
//                        foreach ($tempDatum as $tempItem) {
//                            $t[$mKey] = $tempItem;
//                            $temp[] = $t;
//                        }
//                    }
//                    if($item['id'] == 2){
//                        var_dump(json_encode($groupList,JSON_UNESCAPED_UNICODE));die;
//                    }
//                } else {
//                    $temp[] = $t;
//                }
                if ($groupList) {
                    foreach ($groupList as $groupItem) {
                        $t = array_merge($t, $groupItem);
                        $temp[] = $t;
                    }
//                    if ($item['id'] == 2) {
//                        var_dump(json_encode($groupList, JSON_UNESCAPED_UNICODE));
//                        die;
//                    }
                } else {
                    $temp[] = $t;
                }
            }
            $tempArr = [];
            if ($isEmptyField) {
                foreach ($temp as $tt) {
                    if (!empty($tt[$isEmptyField])) {
                        $tempArr[] = $tt;
                    }
                }
            } else {
                $tempArr = $temp;
            }

            $array[$tag] = $tempArr;
        }

//        var_dump(json_encode($array, JSON_UNESCAPED_UNICODE));
//        die;
        $sheets = new SheetCollection($array);
        $file_path = Storage::path('file.xlsx');
        (new FastExcel($sheets))->export($file_path);
        // 获取文件大小
        $file_size = filesize($file_path);

        // 设置合适的HTTP头
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . basename($file_path) . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . $file_size);

        // 清除输出缓冲
        ob_clean();
        flush();

        // 读取文件并输出到浏览器
        readfile($file_path);

        // 终止脚本
        exit;
    }
}
